import { markRaw } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete } from '@element-plus/icons-vue'
import type Node from 'element-plus/es/components/tree/src/model/node'
import { addModelRequest, delModelRequest } from '@/service/model/model'

/**
 * 添加功能
 * @param data 要追加的子节点的data
 * @param emit 触发更新事件的函数
 */
export async function functionalAppend(data: Tree, emit: (event: string) => void) {
  const result = await ElMessageBox.prompt('请输入子模块的标题', '添加子模块', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S/,
    inputErrorMessage: '标题不能为空',
    draggable: true
  }).catch(() => {
    ElMessage({
      type: 'info',
      message: '取消添加子模块'
    })
    return { value: null }
  })
  if (!result.value) return
  try {
    const value = result.value
    const newModel = {
      modelDescribe: '描述为空',
      modelName: value,
      parentId: data.id
    }
    console.log(newModel)
    await addModelRequest(newModel)
    emit('updateProject')
    ElMessage({
      type: 'success',
      message: `新添加的子模块名:${value}`
    })
  } catch (error) {
    ElMessage({
      type: 'error',
      message: `添加子模块失败: ${error}`
    })
  }
}

/**
 * 移除功能
 * @param node 要删除的节点
 * @param data 要删除的节点的data
 * @param emit 触发更新事件的函数
 */
export function functionalRemove(node: Node, data: Tree, emit: (event: string) => void) {
  ElMessageBox.confirm(`确定继续删除"${data.label}"模块吗?`, 'Warning', {
    type: 'warning',
    icon: markRaw(Delete)
  })
    .then(async () => {
      try {
        console.log(data.id)
        await delModelRequest(data.id)
        emit('updateProject')
        ElMessage({
          type: 'success',
          message: `删除"${data.label}"模块成功`
        })
      } catch (error) {
        ElMessage({
          type: 'error',
          message: `删除"${data.label}"模块失败: ${error}`
        })
      }
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除模块'
      })
    })
}
